package test;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class Solution {
    public String reverseWords(String s) {
        Stack<String> stack = new Stack<>();

        String tmp = "";

        for (int i = 0; i < s.length(); i++) {
            Character c = s.charAt(i);

            tmp += c;

            if (c == ' ' || i == s.length() - 1) {
                tmp = tmp.trim();
                if (!tmp.equals("")) {
                    stack.push(tmp);
                }
                tmp = "";
            }
        }

        StringBuilder sb = new StringBuilder();

        while(!stack.isEmpty()) {
            if (stack.size() == 1) {
                sb.append(stack.pop());
            } else {
                sb.append(stack.pop() + " ");
            }
        }

        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println((new Solution()).reverseWords(" a    b"));
    }
}
